package org.mics.token.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mics.core.model.CurrentUser;
import org.mics.token.annotation.IgnoreToken;
import org.mics.token.config.TokenConfig;
import org.mics.token.config.UserThreadLocal;
import org.mics.token.exception.TokenException;
import org.mics.token.service.TokenService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * token拦截器
 * @author mics
 * @date 2020年5月22日
 * @version  1.0
 */
@Component
@Order(2)
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private TokenService tokenService;
    @Resource
    private TokenConfig tokenConfig;
    /**
     * swagger请求json的方法，该方法以json响应文档信息
     */
    private static final String SWAGGER_JSON_METHOD="openapiJson";
   
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	 IgnoreToken ignoreToken;
         //如果请求不是后台方法不需要验证token
         if (handler instanceof HandlerMethod) {
             ignoreToken = ((HandlerMethod) handler).getMethodAnnotation(IgnoreToken.class);
        	 if( ((HandlerMethod) handler).getMethod().getName().equals(SWAGGER_JSON_METHOD)) {
        		 return true;
        	 }
         } else {
             return true;
         }
         //如果有@IgnoreToken注解，则不验证token
         if (ignoreToken != null) {
             return true;
         }
         //从header中获取token
         String token = request.getHeader(tokenConfig.getHeader());
         //如果header中不存在token，则从参数中获取token
         if (token == null || token.trim().length() == 0) {
             token = request.getParameter(tokenConfig.getHeader());
         }
         //如果参数中不含有token,则从cookies中取
         if (token == null || token.trim().length() == 0) {
        	 Cookie[] cookies = request.getCookies();
        	 if(cookies != null) {
        		 for(int i =0 ;i< cookies.length;i++) {
            		 Cookie cookie = cookies[i];
            		 if(tokenConfig.getHeader().equals(cookie.getName())) {
            			 token = cookie.getValue();
            		 }
            	 }
        	 }
         }
         //token为空
         if (token == null || token.trim().length() == 0) {
             throw new TokenException(401,"登录失效，请重新登录");
         }
         //验证token并记录用户登录账号
         String account = tokenService.verify(token);
         request.setAttribute(tokenConfig.getHeader() + "_Account", account);
         CurrentUser currentUser =  tokenService.getUser(token);
         UserThreadLocal.setUser(currentUser.getId());
         return true;
    }
}
